﻿#pragma execution_character_set("utf-8")
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QCoreApplication>
#include "doubaoapi.h"  // 添加对豆包API的引用
#include "maincontainer.h"
#include "initpage.h"  // 包含初始页面头文件

const QString baiduTokenUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%1&client_secret=%2&";

const char *client_id = "ZOmxvLqBUPZMknP6IkCtGs4S";
const char *secret_id = "mtVbwNLA3SBXQkrbscZRl8MESeZrTybp";
//动物识别专用：
//const QString baiduImageUrl = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=%1";
//通用图像识别：
const QString baiduImageUrl = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=%1";

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    mainContainer(nullptr)
{
    ui->setupUi(this);
}

/**
 * @brief 设置主容器指针
 * @param container 主容器指针
 */
void MainWindow::setMainContainer(MainContainer *container)
{
    this->mainContainer = container;
}

/**
 * @brief 返回初始页面
 * 关闭当前窗口并显示初始选择页面
 */
void MainWindow::returnToInitPage()
{
    this->hide();
    if (returnPage) {
        returnPage->show();
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

// 手动确认按钮点击事件
void MainWindow::on_pushButton_manual_clicked()
{
    QString manualKeyword = ui->lineEdit_keyword->text().trimmed();
    if(manualKeyword.isEmpty()) {
        QMessageBox::information(this, "提示", "请输入关键词");
        return;
    }
    
    currentKeyword = manualKeyword;
    ui->label_2->setText("已手动设置为: " + currentKeyword + "\n点击重新搜索按钮进行AI查询");
}

// 重新搜索按钮点击事件
void MainWindow::on_pushButton_research_clicked()
{
    if(currentKeyword.isEmpty()) {
        QMessageBox::information(this, "提示", "请先识别图片或手动输入关键词");
        return;
    }
    
    ui->label_2->setText("正在重新搜索...");
    
    // 调用豆包API询问垃圾类型
    DoubaoAI doubaoAI;
    QString question = "\"" + currentKeyword + "\"属于什么垃圾类型？只需要回答类型（可回收物、有害垃圾、湿垃圾、干垃圾）即可，不要回答其他的内容";
    QString aiResponse = doubaoAI.DoubaoAI_request(question);
    
    QString result = "   手动输入结果：\n";
    result += "────────────────\n";
    result += QString("   %1\n").arg(currentKeyword);
    result += aiResponse;
    
    ui->label_2->setText(result);
}

// 修改原有的识别函数，保存识别到的关键词
void MainWindow::on_pushButton_clicked()
{
    ui->label_2->setAlignment(Qt::AlignCenter);
    ui->label_2->setText("正在努力识别~");

    QByteArray img = Image::imgToBase64(imgPath);
    QByteArray imgData = "image=" + img;
    //获取access_token
    QByteArray replyData;//保存回复信息

    QString url = QString(baiduTokenUrl).arg(client_id).arg(secret_id);


    QMap<QString,QString> header;//封装了一个头部信息
    header.insert(QString("Content-Type"),QString("application/x-www-form-urlencoded"));


    QString accessToken;

    bool result = Http::post_sync(url,header,imgData,replyData);
    if(result)
    {
        QJsonObject obj = QJsonDocument::fromJson(replyData).object();
        accessToken = obj.value("access_token").toString();

    }

    replyData.clear();

    QString imgUrl = baiduImageUrl.arg(accessToken);
    result = Http::post_sync(imgUrl,header,imgData,replyData);

    if(result)
    {
        QJsonObject obj = QJsonDocument::fromJson(replyData).object();
        QJsonValue val = obj.value("result");
        if(val.isArray())
        {
            QJsonArray arr = val.toArray();
            QString result = "   图片识别结果：\n";
            result += "────────────────\n";

            QJsonValue item = arr.at(0);
            if(item.isObject())
            {
                QJsonObject obj = item.toObject();
                QString keyword = obj.value("keyword").toString();
                // 保存识别到的关键词
                currentKeyword = keyword;
                // 正确处理置信度分数
                double score = 0.0;
                if(obj.contains("score")) {
                    if(obj["score"].isString()) {
                        score = obj["score"].toString().toDouble();
                    } else if(obj["score"].isDouble()) {
                        score = obj["score"].toDouble();
                    }
                }

                // 将分数转换为百分比形式
                double percent = score * 100;
                result += QString("   %1 - %2%\n")
                                  .arg(keyword)
                                  .arg(percent, 0, 'f', 1);  // 修正格式字符，将'f-'改为'f'
                    
                    // 调用豆包API询问这是什么垃圾
                    DoubaoAI doubaoAI;
                    // 修改提问方式，使其更直接明确
                    QString question = "\"" + keyword + "\"属于什么垃圾类型？只需要回答类型（可回收物、有害垃圾、湿垃圾、干垃圾）即可，不要回答其他的内容";
                    QString aiResponse = doubaoAI.DoubaoAI_request(question);
                    result += QString(aiResponse);
                }
           // }
            ui->label_2->setWordWrap(true);  // 启用自动换行

            ui->label_2->setText(result);
            return;
        }

    }
    ui->label_2->setText("无法识别，\n看看是不是图片格式出错了~");
}


void MainWindow::on_pushButton_2_clicked()
{
    imgPath = QFileDialog::getOpenFileName(this, "选择图片", QCoreApplication::applicationDirPath());
    if(imgPath.isEmpty())
    {
        QMessageBox::warning(this, "提示", "还没选图片呢");
        ui->label_2->setText("这次又是什么呢~");
    }

    QPixmap pix(imgPath);
    // 缩放图片以适应label，保持纵横比
    QPixmap scaledPix = pix.scaled(ui->label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->label->setPixmap(scaledPix);
    // 确保label不自动拉伸图片
    ui->label->setScaledContents(false);
}

// 返回按钮点击事件槽函数
void MainWindow::on_pushButton_back_clicked()
{
    if (mainContainer) {
        mainContainer->switchToPage(MainContainer::InitPageIndex);
    }
}

